#include "Food.h"
#include <graphics.h>
#include <tchar.h>
#include <Windows.h>
#include <random>

#define block_width 20
#define x_origin 0
#define y_origin 0

Food::Food(const std::vector<std::vector<int>>& snakeBody) {
    static std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_int_distribution<> disX(4, 23);
    static std::uniform_int_distribution<> disY(4, 19);

    bool test = false;
    position.resize(2);
    do {
        position[0] = disX(gen);
        position[1] = disY(gen);
        test = false;
        for (const auto& pos : snakeBody) {
            if (pos == position) {
                test = true;
                break;
            }
        }
    } while (test);
}

void Food::drawUnitBlock(int body_x, int body_y, const char* pic) {
    int left = body_x * block_width + x_origin;
    int top = body_y * block_width + y_origin;
    IMAGE img;
    int len = MultiByteToWideChar(CP_ACP, 0, pic, -1, NULL, 0);
    wchar_t* wPic = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, pic, -1, wPic, len);
    loadimage(&img, wPic, block_width, block_width);
    delete[] wPic;
    putimage(left, top, &img);
}

void Food::draw() {
    drawUnitBlock(position[0], position[1], "food.png");
}

std::vector<int> Food::getPosition() {
    return position;
}

void Food::regenerate(const std::vector<std::vector<int>>& snakeBody) {
    static std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_int_distribution<> disX(4, 23);
    static std::uniform_int_distribution<> disY(4, 19);

    bool test = false;
    do {
        position[0] = disX(gen);
        position[1] = disY(gen);
        test = false;
        for (const auto& pos : snakeBody) {
            if (pos == position) {
                test = true;
                break;
            }
        }
    } while (test);
}